package middleware

import (
	"crypto/md5"
	"fmt"
	"net/http"

	"minipromgr/internal/database"
	"minipromgr/internal/models"

	"github.com/gin-gonic/gin"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 检查session或token
		sessionID, err := c.Cookie("session_id")
		if err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "未授权访问"})
			c.Abort()
			return
		}

		// 简单的session验证（实际项目中应该使用更安全的方式）
		var user models.User
		if err := database.DB.Where("username = ?", sessionID).First(&user).Error; err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "无效的session"})
			c.Abort()
			return
		}

		c.Set("user", user)
		c.Next()
	}
}

func CORSMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Header("Access-Control-Allow-Origin", "http://localhost:8080")
		c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
		c.Header("Access-Control-Allow-Headers", "Content-Type, Authorization")
		c.Header("Access-Control-Allow-Credentials", "true")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.Next()
	}
}

func HashPassword(password string) string {
	hash := md5.Sum([]byte(password))
	return fmt.Sprintf("%x", hash)
}

func VerifyPassword(password, hash string) bool {
	return HashPassword(password) == hash
}
